//@Author: wulinlin
//@Description:
//@File:  serverContext
//@Version: 1.0.0
//@Date: 2023/03/09 14:30

package svc

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"pingbuqingyun_django/app/models/dao"
	"pingbuqingyun_django/pkg/tools"
	"pingbuqingyun_django/pkg/validators"
	"time"

	"gorm.io/gorm"

	"pingbuqingyun_django/app/config"
	"pingbuqingyun_django/routes"
)

var svc *ServiceContext

type ServiceContext struct {
	Config    *config.Config
	Server    *gin.Engine
	MysqlConn *gorm.DB
	Trans     ut.Translator
}

func NewServiceContext(path string) (svc *ServiceContext) {
	cfg := config.NewConfig(path)
	//gormConf := &gorm.Config{}
	//err := tools.OpenDB("SQLite",cfg.MySQl.Datasource, gormConf, 10, 20, dao.ModelList...)
	gormLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold:             time.Second, // 慢查询阈值
			LogLevel:                  logger.Info,
			IgnoreRecordNotFoundError: true,
			Colorful:                  false, // 禁止彩色打印
		},
	)
	gormConf := &gorm.Config{
		Logger: gormLogger,
	}
	err := tools.OpenDB("SQLite", "sqlite.db", gormConf, 10, 20, dao.ModelList...)
	//err := tools.OpenDB("Mysql", "xzl:Xzl4kyk!@tcp(192.168.1.45:3306)/qcc_company_graph?charset=utf8mb4&parseTime=True&loc=Local", gormConf, 10, 20, dao.ModelList...)
	if err != nil {
		panic(any(err))
		return nil
	}
	return &ServiceContext{
		Config:    cfg,        //
		MysqlConn: tools.DB(), // 集成MySQL查询对象
		//MysqlConn: NewSQLiteConn(), // 集成SQLite查询对象
		Server: routes.RegisterRouter(),
		Trans:  validators.InitTrans(cfg.Local),
	}
}

//func NewSQLiteConn() *gorm.DB{
//	db, err := gorm.Open(sqlite.Open("ludaxianfeng.db"), &gorm.Config{})
//
//	if err != nil{
//		panic(err)
//	}
//	db.AutoMigrate(dao.ModelList...)
//	return db
//}

func (s *ServiceContext) BeforeStart() error {

	/** 注册验证器*/
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		_ = v.RegisterValidation("mobile", validators.ValidatePhone)
		// 对认证器进行翻译
		//_ = v.RegisterTranslation("mobile", s.Trans, func(ut ut.Translator) error {
		_ = v.RegisterTranslation("mobile", validators.InstanceTrans, func(ut ut.Translator) error {
			return ut.Add("mobile", "{0} 手机号码格式校验不通过！", true)
		}, func(ut ut.Translator, fe validator.FieldError) string {
			t, _ := ut.T("mobile", fe.Field())
			return t
		})
	}
	//err := s.Server.Run(addr)
	//if err != nil {
	//	return err
	//}
	return nil
}
